<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/jquery-3.3.1.min.js"></script>
    <style>
        #box{
            width: 500px;
            background: pink;
            text-align: center;
        }
        .infoBox{
            text-align:left;
            position: relative;
            left: 62px;
        }
        #message{
            width: 322px;
        }
        #send{
            position:relative;
            left:50px;
            height:30px;
            width: 326px;
        }
    </style>
</head>
<body>
<div id="box">
    <p>蜗牛聊天室</p>
    <textarea rows="10" cols="50" disabled="disabled" id="textarea"></textarea><br>
    <div class="infoBox">
        用户名:<input type="text" id="userName"><br><br>
        <button style="color: green;" id="join">加入聊天室</button>
        &nbsp;&nbsp;&nbsp;&nbsp;
        <button style="color: red;" id="out">离开聊天室</button>
    </div>
    <br><br>
    <div class="infoBox">
        消&nbsp;&nbsp;&nbsp;息:<input type="text" id="message"><br><br>
        <button id="send">发送消息</button>
    </div>
    <br>
</div>
<script>
    let url = "ws:192.168.8.128:8080/WebsocketController/"
    var ws = null;
    $("#join").click(function () {
        //1.获取昵称、账号
        var userName = $("#userName").val();
        url = url + userName;	//传递用户名
        console.info(url);
        //2.建立连接    如果得到对象说明连接成功
        ws = new WebSocket(url);

        //3.绑定各个事件
        //3.1
        ws.onopen = function () {
            console.log("连接成功")
        }
    })
        //3.2
        ws.onmessage = function (result) {
            var textarea = document.getElementById('message');
            textarea.append(result.data+"\n");
            //将文本域的滚动条滚动到最后
            textarea.scrollTop = textarea.scrollHeight;
        }

        //3.3 error
        ws.onerror = function () {
            console.log("网络异常")
        }

        //3.4
        ws.onclose = function () {
            $("#message").append("用户:"+userName+"离开聊天室"+"\n");
            console.info("关闭连接");
        }

        //发送消息
        $("#send").click(function(){
            //将输入框中的消息发送给服务器，并且显示到消息框中
            var messageInput = $("#textarea");
            var message = messageInput.val();
            if(ws!=null){
                ws.send(message);	//发送消息
                //清空
                messageInput.val("");
            }
        });

        //断开连接
        $("#out").click(function(){
            if(ws!=null){
                ws.close();
            }
        });

</script>
</body>
</html>